from openai import OpenAI
from flask import Flask, request, jsonify
import time

app = Flask(__name__)

# 设置 OpenAI API 密钥
client = OpenAI(
    api_key="Your API Key",  # 确保替换为有效的 API 密钥
    base_url="https://api.chatanywhere.tech/v1"
)

# 定义可用功能列表及其路径
available_functions = {
    "/api/translate_en_to_zh": "Translate English text to Chinese",
    "/api/translate_zh_to_en": "Translate Chinese text to English",
    "/api/summarize": "Summarize the given text"
}

# 获取所有功能列表的接口
@app.route('/api/functions', methods=['GET'])
def get_functions():
    return jsonify({"functions": available_functions})

# 调用 GPT 模型进行英译中
@app.route('/api/translate_en_to_zh', methods=['POST'])
def translate_en_to_zh():
    data = request.json
    text = data.get("text")
    try:
        response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "Translate English to Chinese."},
                {"role": "user", "content": text}
            ],
            timeout=30  # 设置超时时间为 30 秒
        )
        return jsonify({"result": response.choices[0].message.content})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# 调用 GPT 模型进行中译英
@app.route('/api/translate_zh_to_en', methods=['POST'])
def translate_zh_to_en():
    data = request.json
    text = data.get("text")
    try:
        response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "Translate Chinese to English."},
                {"role": "user", "content": text}
            ],
            timeout=30  # 设置超时时间为 30 秒
        )
        return jsonify({"result": response.choices[0].message.content})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# 调用 GPT 模型进行文本总结
@app.route('/api/summarize', methods=['POST'])
def summarize():
    data = request.json
    text = data.get("text")
    try:
        response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "Summarize the following text."},
                {"role": "user", "content": text}
            ],
            timeout=30  # 设置超时时间为 30 秒
        )
        return jsonify({"result": response.choices[0].message.content})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    app.run(debug=False)